$(function() {

var gConfig = new Config();
var gRule = new Rule();

gRule.addUpdateListener(function(theRule) {
	var rules = theRule.getData();
	$("tbody", "#ruleTable").empty();
	gRule.traverse(function(r) {
		var tr = $("#ruleModel").clone();
		tr.removeAttr("id").css("display", "");
		$("td[name='name']", tr).text(r.name);
		$("td[name='inc']", tr).text(r.inc);
		$("td[name='exc']", tr).text(r.exc);
		$("td[name='cancel'] > input", tr).attr((r.cancel ? "checked" : "nocheck"), "checked");
		$("td[name='cache'] > input", tr).attr((r.cache ? "checked" : "nocheck"), "checked");
		$("td[name='edit'] > button", tr).click(function() {
			$("#ruleName").val($("td[name='name']", tr).text());
			$("#ruleInc").val($("td[name='inc']", tr).text());
			$("#ruleExc").val($("td[name='exc']", tr).text());
			$("#ruleCancel").removeAttr("checked").
			attr($("td[name='cancel'] > input", tr).attr("checked") ? "checked" : "nochk", "checked");
			$("#ruleCache").removeAttr("checked")
			.attr($("td[name='cache'] > input", tr).attr("checked") ? "checked" : "nochk", "checked");
		});
		$("td[name='delete'] > button", tr).click(function() {
			var name = $("td[name='name']", tr).text();
			tr.remove();
			for (var i = 0; i < rules.length; i++) {
				if (rules[i].name == name) {
					rules.splice(i, 1);
					i--;
				}
			}
			gRule.saveToDb(rules);
		});
		$("tbody", "#ruleTable").append(tr);
	});
});

function initi18n() {
	$("[message]").each(function(index, elem) {
		var node = $(elem);
		var message = node.attr("message");
		node.text(chrome.i18n.getMessage(message));
	});
}

function initUi() {
	initi18n();
}

$("#addRuleBtn").click(function() {
	var cancel = $("#ruleCancel");
	var cache = $("#ruleCache");

	var rule = {
		"name": $("#ruleName").val(),
		"inc": $("#ruleInc").val(),
		"exc": $("#ruleExc").val(),
		"cancel": cancel.attr("checked") ? true : false,
		"cache": cache.attr("checked") ? true : false
	};
	// console.log(rule);
	gRule.saveRule(rule);
});

$("#clearBtn").click(function() {
	chrome.storage.local.clear(function() {});
});

$("#getByteUseBtn").click(function() {
	chrome.storage.local.getBytesInUse(null, function(bytesInUse) {
		console.log("ByteInUse: %d", bytesInUse);
	});
});

$("#showAllBtn").click(function() {
	console.log(gRule.data);
});

$("#exportBtn").click(function() {
	window.webkitRequestFileSystem(window.TEMPORARY, 1024 * 1024, function(fs) {
		fs.root.getFile("config.json", { "create": true }, function(file) {
			file.createWriter(function(writer) {
				var builder = new WebKitBlobBuilder();
				builder.append($.toJSON(gConfig.getData()));
				var blob = builder.getBlob("text/plain");
				writer.onwriteend = function () {
					chrome.tabs.create({ "url": file.toURL(), "selected": true });
				};
				writer.write(blob);
			});
		});
	}, function(error) {
	});
});

$("#importBtn").click(function() {
	$("#file").click();
});

$("#file").change(function(event) {
	var files = event && event.target && event.target.files;
	if (!files) {
		return;
	}
	
	for (var i = 0, n = files.length; i < n; i++) {
		var reader = new FileReader();
		reader.onload = function(f) {
			var cont = f && f.target && f.target.result;
			console.log(cont);
			var data = jQuery.parseJSON(cont);
			if (!data) {
				return;
			}
			gConfig.setData(data);
		};
		reader.readAsText(files[i]);
	}
});

$("#checkurl").click(function() {
	var regex = $("#regex").val();
	var url = $("#url").val();
	if (new RegExp(regex).test(url)) {
		alert("ok");
	} else {
		alert("fail");
	}
});

initUi();
gConfig.addData(gRule);
gConfig.loadFromDb();

});
